package com.lovcreate.shop.mgt.util;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 * 文件名：IpUtil.java
 * 创建人：lvjx
 * 创建日期: 2016-12-22 13:51
 * 描  述：获取ip
 * 版本号：1.0
 */
public class IpUtil {

    /**
     *
     *  @Description    : 获取客户端ip地址
     *  @Method_Name    : getIpAddr
     *  @param request
     *  @return
     *  @return         : String
     *  @Creation Date  : 2015-6-2 下午1:04:07
     *  @version        : v1.00
     *  @Author         : ljx
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 多个路由时，取第一个非unknown的ip
        String[] arr = ip.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ip = str;
            }
            break;
        }
        return ip;
    }

    /**
     *
     *  @Description    : 获取ip macaddress
     *  @Method_Name    : getMACAddress
     *  @param ip
     *  @return
     *  @return         : String
     *  @Creation Date  : 2015-6-2 下午1:04:40
     *  @version        : v1.00
     *  @Author         : ljx
     */
    public static String getMACAddress(final String ip) {
        String str = "";
        String macAddress = "";
        try {
            Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
            InputStreamReader ir = new InputStreamReader(p.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {
                    if (str.indexOf("MAC Address") > 1) {
                        macAddress = str.substring(
                                str.indexOf("MAC Address") + 14, str.length());
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return macAddress;
    }
}
